using System.Data;
using Admin2025.Application.Dtos;
using Admin2025.Application.IServices;
using Dapper;

namespace Admin2025.Application.Services;

public class RoleManagementService : IRoleManagementService
{
  private readonly IDbConnection _db;

  public RoleManagementService(IDbConnection db)
  {
    _db = db;
  }

  public async Task<bool> AssignRoleToUserAsync(Guid userId, Guid roleId)
  {
    var sql = "INSERT INTO UserRoles (UserId, RoleId) VALUES (@UserId, @RoleId)";
    return await _db.ExecuteAsync(sql, new { UserId = userId, RoleId = roleId }) > 0;
  }

  public async Task<bool> RemoveRoleFromUserAsync(Guid userId, Guid roleId)
  {
    var sql = "DELETE FROM UserRoles WHERE UserId = @UserId AND RoleId = @RoleId";
    return await _db.ExecuteAsync(sql, new { UserId = userId, RoleId = roleId }) > 0;
  }

  public async Task<bool> CreateRoleAsync(CreateRoleDto dto)
  {
    var sql = "INSERT INTO AppRoles (Id, RoleName, Description, DataScope) VALUES (@Id, @RoleName, @Description, @DataScope)";
    return await _db.ExecuteAsync(sql, new
    {
      Id = Guid.NewGuid(),
      dto.RoleName,
      dto.Description,
      dto.DataScope
    }) > 0;
  }

  public async Task<bool> UpdateRoleAsync(Guid roleId, UpdateRoleDto dto)
  {
    var sql = "UPDATE AppRoles SET Description = @Description, DataScope = @DataScope WHERE Id = @Id";
    return await _db.ExecuteAsync(sql, new { Id = roleId, dto.Description, dto.DataScope }) > 0;
  }

  public async Task<bool> DeleteRoleAsync(Guid roleId)
  {
    var sql = "DELETE FROM AppRoles WHERE Id = @Id";
    return await _db.ExecuteAsync(sql, new { Id = roleId }) > 0;
  }

  public async Task<bool> AssignPermissionToRoleAsync(Guid roleId, Guid permissionId)
  {
    var sql = "INSERT INTO RolePermissions (RoleId, PermissionId) VALUES (@RoleId, @PermissionId)";
    return await _db.ExecuteAsync(sql, new { RoleId = roleId, PermissionId = permissionId }) > 0;
  }

  public async Task<bool> RemovePermissionFromRoleAsync(Guid roleId, Guid permissionId)
  {
    var sql = "DELETE FROM RolePermissions WHERE RoleId = @RoleId AND PermissionId = @PermissionId";
    return await _db.ExecuteAsync(sql, new { RoleId = roleId, PermissionId = permissionId }) > 0;
  }
}